﻿
#include "../iocp/IOCP/fileio.h"
#include "pipehandles.h"
#include "tcphandles.h"
#include "iocpsrv.h"
#include "header_def.h"
#include <process.h>

THREADPOOL gThreadPool = NULL;

CIocpSrv::CIocpSrv()
    : m_hIocp(nullptr)
    , m_bInit(FALSE)
{
}

CIocpSrv::~CIocpSrv()
{
    if (m_hIocp)
    {
        iobase_free(m_hIocp);
        m_hIocp = nullptr;
    }

    m_bInit = FALSE;
}

BOOL CIocpSrv::InitEnv()
{
    if (nullptr != m_hIocp)
    {
        return FALSE;
    }

    if (FALSE == m_bInit && FALSE == iocp_init_env())
    {
        return FALSE;
    }

    THREADPOOL_CONFIG* config = threadpool_config_new();
    config->priority_count = 2;
    config->queue_max_num = 1024;
    config->max_timer_count = 64;
    config->max_thread_num = 8;
    config->thread_num = 4;
    gThreadPool = threadpool_create(config);
    threadpool_config_free(config);

    m_bInit = TRUE;
    m_hIocp = iobase_new();

    if (nullptr == m_hIocp)
    {
        return FALSE;
    }
    return TRUE;
}

void CIocpSrv::UninitEnv()
{
    if (m_hIocp)
    {
        iobase_loopexit(m_hIocp);
    }

    if (m_hIocp)
    {
        iobase_free(m_hIocp);
        m_hIocp = nullptr;
    }

    if (m_bInit)
    {
        iocp_uninit_env();
    }
    m_bInit = FALSE;
    if (gThreadPool)
    {
        threadpool_destroy(gThreadPool);
        gThreadPool = NULL;
    }
    
}

unsigned CIocpSrv::Dispatch()
{
    HIOCPFILE hPipe = pipe_listen(m_hIocp);
    HIOCPFILE hTcp = tcp_listen(m_hIocp);

    iobase_dispatch(m_hIocp); //消息循环
    // 准备退出了

    tcp_listen_close(hTcp);
    pipe_listen_close(hPipe);

    return 0;
}

void CIocpSrv::Exit()
{
    if (m_hIocp)
    {
        iobase_loopexit(m_hIocp);
        m_hIocp = NULL;
    }
}